﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.LoadCustomers();

    }
    protected void LoadCustomers()
    {
        try
        {
            MembershipUserCollection allUsers = Membership.GetAllUsers();
            MembershipUserCollection filteredUsers = new MembershipUserCollection();


            // If we are filtering by role, get the users in the specified role
            string[] usersInRole = Roles.GetUsersInRole("Customer");

            // For each user in the role, add the user details to filteredUsers
            foreach (MembershipUser user in allUsers)
            {
                foreach (string userInRole in usersInRole)
                {
                    if (userInRole == user.UserName)
                    {
                        filteredUsers.Add(user);
                        break; // Breaks out of the inner foreach loop to avoid unneeded checking.
                    }
                }
            }


            this.GridViewCustomers.DataSource = filteredUsers;
            this.GridViewCustomers.DataBind();
        }
        catch
        {
        }
    }
    protected void Click_Logout(object sender, EventArgs e)
    {
        System.Web.Security.FormsAuthentication.SignOut();
        Response.Redirect("~/Login.aspx");
    }
    protected void CreatedUser(object sender, EventArgs e)
    {
        //Using LINQ, add the additonal employee information to the database, and link it to the ASP user
        using (TimeTrackerDataContext context = new TimeTrackerDataContext())
        {
            Employee tempEmployee = new Employee
            {
                emailAddress = CreateUserWizardMain.Email,
                firstName = ((TextBox)CreateUserWizardMain.CreateUserStep.ContentTemplateContainer.FindControl("FirstName")).Text,
                lastName = ((TextBox)CreateUserWizardMain.CreateUserStep.ContentTemplateContainer.FindControl("LastName")).Text,
                userID  = (System.Guid)System.Web.Security.Membership.GetUser(CreateUserWizardMain.UserName).ProviderUserKey
            };
            context.Employees.InsertOnSubmit(tempEmployee);
            context.SubmitChanges();
        }
        System.Web.Security.Roles.AddUserToRole(CreateUserWizardMain.Email, "Employee");
    }

    protected void CreatedCustomerUser(object sender, EventArgs e)
    {
        //Using LINQ, add the additonal employee information to the database, and link it to the ASP user
        Guid userID = (System.Guid)System.Web.Security.Membership.GetUser(CreateCustomerUserWizard.UserName).ProviderUserKey;

        TimeTrackerDataContext context = new TimeTrackerDataContext();
        CompanyUser userLink = new CompanyUser();


        userLink.CustomerId = Convert.ToInt32(DropDownListCustomers.SelectedValue);
        userLink.UserId = userID;

        context.CompanyUsers.InsertOnSubmit(userLink);
        context.SubmitChanges();

        System.Web.Security.Roles.AddUserToRole(CreateCustomerUserWizard.Email, "Customer");
    }

    protected void CreatingUser(object sender, LoginCancelEventArgs e)
    {
        //Assign the email address to the username, since we're using them as the same thing
        CreateUserWizardMain.UserName = CreateUserWizardMain.Email;
    }
    protected void CreatingCustomerUser(object sender, LoginCancelEventArgs e)
    {
        //Assign the email address to the username, since we're using them as the same thing
        CreateCustomerUserWizard.UserName = CreateCustomerUserWizard.Email;
        
    }
    protected void CreateUser(object sender, EventArgs e)
    {
        //Display the Wizard after the link has been clicked
        CreateUserWizardMain.Visible = true;
        GridView1.Visible = false;
        LinkButtonCreateEmp.Visible = false;
        this.PanelCustomer.Visible = false;
    }
    protected void CreateCustomerUser(object sender, EventArgs e)
    {
        //Display the Wizard after the link has been clicked
        CreateCustomerUserWizard.Visible = true;
        this.PanelEmployee.Visible = false;
        GridViewCustomers.Visible = false;
        LinkButtonCreateCustomer.Visible = false;
    }
    

    protected void EmployeeCommand(object sender, GridViewCommandEventArgs e)
    {
        switch (e.CommandName)
        {
            case "ChangeRole":
                int index = Convert.ToInt32(e.CommandArgument);

                GridViewRow row = GridView1.Rows[index];

                if (System.Web.Security.Roles.IsUserInRole(row.Cells[5].Text, "Administrator"))
                    System.Web.Security.Roles.RemoveUserFromRole(row.Cells[5].Text, "Administrator");
                else
                    System.Web.Security.Roles.AddUserToRole(row.Cells[5].Text, "Administrator");

                GridView1.DataBind();
                
                break;
            default:
                break;
        }
    }
    protected void CustomerCommands(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "UserDelete")
        {
            string username = GridViewCustomers.DataKeys[int.Parse(e.CommandArgument.ToString())].Value.ToString();
            MembershipUser user = Membership.GetUser(GridViewCustomers.DataKeys[int.Parse(e.CommandArgument.ToString())].Value.ToString());

            TimeTrackerDataContext context = new TimeTrackerDataContext();
            var compUser = (from cu in context.CompanyUsers
                            where cu.UserId == (Guid)user.ProviderUserKey
                            select cu).Single();
            context.CompanyUsers.DeleteOnSubmit(compUser);
            context.SubmitChanges();

            Membership.DeleteUser(user.UserName);
            Response.Redirect("Users.aspx");
        }

    }
    protected string GetCustomerName(string userName)
    {
        TimeTrackerDataContext context = new TimeTrackerDataContext();
        MembershipUser user = Membership.GetUser(userName);
        var companyName = (from cu in context.CompanyUsers
                           join c in context.Customers on cu.CustomerId equals c.id
                           where cu.UserId == (Guid)user.ProviderUserKey
                           select c.customerName);
        
        return companyName.Single();
    }
    protected void EditPersonalProfile(object sender, EventArgs e)
    {
        this.PanelCustomer.Visible = false;
        this.PanelEmployee.Visible = false;
        this.PanelPersonal.Visible = true;

        TimeTrackerDataContext context = new TimeTrackerDataContext();

        MembershipUser user = Membership.GetUser();

        Employee emp = (from em in context.Employees
                        where em.userID == (Guid)user.ProviderUserKey
                        select em).Single();

        this.TextBoxEmail.Text= emp.emailAddress;
        this.TextBoxFirstName.Text = emp.firstName;
        this.TextBoxLastName.Text = emp.lastName;


    }
    protected void btnSubmitProfile(object sender, EventArgs e)
    {
        TimeTrackerDataContext context = new TimeTrackerDataContext();

        MembershipUser user = Membership.GetUser();

        Employee emp = (from em in context.Employees
                        where em.userID == (Guid)user.ProviderUserKey
                        select em).Single();

        emp.lastName = TextBoxLastName.Text;
        emp.firstName = TextBoxFirstName.Text;
        emp.emailAddress = TextBoxEmail.Text;


        user.Email = TextBoxEmail.Text;
        
        Membership.UpdateUser(user);

        context.SubmitChanges();

    }
}
